<?php
/**
 * swoole_http服务
 */
class HTTPserver 
{
  
  CONST HOST = '0.0.0.0';
  CONST PROT =  8811;
  public $http = null;

  public function __construct()
  {
    $this->http = new swoole_http_server(self::HOST,self::PROT);
    $this->http->set([
          'enable_static_handler'=>true,
          'worker_num'=>5,
    ]);

    $this->http->on('start',[$this,'OnStart']);
    $this->http->on('WorkerStart',[$this,'OnWorkerStart']);
    $this->http->on('request',[$this,'OnRequest']);  
    $this->http->start();

  }

  
  /**
   * 功能:     主进程别称
   * @Author   Mrzhp
   * @email    18702529695@163.com
   * @DateTime 2018-07-09
   * @param    [type]              $server [description]
   */
  public function OnStart($server)
  {
    swoole_set_process_name('thinkphpid');
  }


   public function OnWorkerStart(swoole_server $server, int $worker_id){

      // 应用目录
     define('APP_PATH', __DIR__.'/../application/');
     // 定义配置文件目录和应用目录同级
     define('CONF_PATH', __DIR__.'/../config/');
      // 加载框架里面的引导文件
     require __DIR__ . '/../thinkphp/base.php';

   }

   public function OnRequest($request,$response){

      $_SERVER = [];
      if (isset($request->server)) {
          foreach ($request->server as $key => $value) {
            $_SERVER[strtoupper($key)] = $value;
          }
      }
    

     if (isset($request->header)) {
          foreach ($request->header as $key => $value) {
            $_SERVER[strtoupper($key)] = $value;
          }
      }

      $_GET = [];
      if (isset($request->get)) {
          foreach ($request->get as $key => $value) {
            $_GET[$key] = $value;
          }
      }

      $_POST = [];
      if (isset($request->post)) {
          foreach ($request->post as $key => $value) {
            $_POST[$key] = $value;
          }
      }



    ob_start();
    try{
      think\App::run()->send();
     }catch (\Exception $e){
     }


     $res = ob_get_contents();
     ob_end_clean();
     $response->end($res);
  }



}


$obj = new HTTPserver();
